package cn.luischen.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.luischen.config.UploadConfig;
import cn.luischen.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class FileUtil {


    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String renameToUUID(String fileName) {
        if (null == fileName) {
            throw BusinessException.withErrorCode("upload fileName not null!");
        }
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String uploadFileGetWebPath(MultipartFile file, String user) {
        if (null == file) {
            throw BusinessException.withErrorCode("upload file not null!");
        }
        String fileName = renameToUUID(file.getOriginalFilename());
        String filePath = user + "/" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/";
        UploadConfig uploadConfig = SpringContextUtil.getBean(UploadConfig.class);
        String uploadPath = uploadConfig.getUploadPath();
        String fullPath = uploadPath + filePath;
        try {
            uploadFile(file.getBytes(), fullPath, fileName);
        } catch (Exception e) {
            log.error("上传文件异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return "/files/" + filePath + fileName;
    }

}
